package social.hub.oauth.oauth4j;

import java.util.ArrayList;
import java.util.List;

import org.oauth4j.core.OAuth4JService.Method;
import org.oauth4j.core.OAuth4JService.Protocol;
import org.oauth4j.core.OAuth4JServiceProvider;
import org.oauth4j.core.OAuth4JServiceProviderService;
import org.oauth4j.core.SimpleOAuth4JSPService;

import social.hub.oauth.OAuthServiceConfig;
import social.hub.util.UrlBuilder;

public class GenericOAuth4JServiceProvider implements OAuth4JServiceProvider {

	private OAuthServiceConfig serviceConfig;

	@Override
	public OAuth4JServiceProviderService getAccessTokenEndpoint() {

		String url = buildUrl(serviceConfig.getAccessTokenUrl());

		return new SimpleOAuth4JSPService(Protocol.HTTPS, Method.GET, url, String.class, 0);

	}

	@Override
	public OAuth4JServiceProviderService getAuthorizeTokenEndpoint() {

		String url = buildUrl(serviceConfig.getAuthorizeUrl());

		return new SimpleOAuth4JSPService(Protocol.HTTPS, Method.GET, url, String.class, 0);

	}

	@Override
	public OAuth4JServiceProviderService getRequestTokenEndpoint() {

		String url = buildUrl(serviceConfig.getRequestTokenUrl());

		return new SimpleOAuth4JSPService(Protocol.HTTPS, Method.GET, url, String.class, 0);

	}

	@Override
	public <S extends OAuth4JServiceProviderService> List<S> getServices() {
		return (List<S>) new ArrayList<S>();
	}

	public void setServiceConfig(OAuthServiceConfig serviceConfig) {
		this.serviceConfig = serviceConfig;
	}

	private String buildUrl(String url) {

		UrlBuilder urlBuilder = new UrlBuilder(url);
		urlBuilder.addUrlParan("appId", serviceConfig.getAppId());
		urlBuilder.addUrlParan("apiKey", serviceConfig.getApiKey());
		urlBuilder.addUrlParan("apiSecret", serviceConfig.getApiSecret());
		urlBuilder.addUrlParan("callbackUrl", serviceConfig.getCallbackUrl());
		return urlBuilder.toString();

	}

}